﻿using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Text;

using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

using BestHTTP;
using BestHTTP.WebSocket;
using BestHTTP.Cookies;
using pEventBus;
using Google.Protobuf;
using Google.Protobuf.Collections;

using Io.Marsdigital.CommonProtocol.Pb;
using Com.Shinian.FcgProtocol.Pb;
using FCG.cache.proxy_model; 
using barreleye.cache.proxy_model;
using Network;
using GF.Debug;


public class WebSocketManager : MonoSingleton<WebSocketManager>
{
    List<TimeTrigger> triggers = new List<TimeTrigger>();
    public List<IProxyModelHandler> pmHandlers = new List<IProxyModelHandler>();

    public void ClearData()
    {
        fcgProxyModelHandler().caches.Remove(FCG.cache.proxy_model.ProxyModelIndex.FightScenePM);
        fcgProxyModelHandler().caches.Add(FCG.cache.proxy_model.ProxyModelIndex.FightScenePM, new FightScenePM());
    }

    protected override void Init()
    {
        pmHandlers.Add(new FCG.cache.proxy_model.ProxyModelHandler());
        pmHandlers.Add(new barreleye.cache.proxy_model.ProxyModelHandler());
    }

    public GameSystemPM GameSystemPM()
    {
        return barreleyeProxyModelHandler().GameSystemPM();

    }

    public PlayerPM PlayerPM()
    {
        return fcgProxyModelHandler().PlayerPM();
    }

    public CardPackPM CardPackPM()
    {
        return fcgProxyModelHandler().CardPackPM();
    }

    public FightScenePM FightScenePM()
    {
        return fcgProxyModelHandler().FightScenePM();
    }

    public FCG.cache.proxy_model.ProxyModelHandler fcgProxyModelHandler()
    {
        return (FCG.cache.proxy_model.ProxyModelHandler)pmHandlers[0];
    }

    public barreleye.cache.proxy_model.ProxyModelHandler barreleyeProxyModelHandler()
    {
        return (barreleye.cache.proxy_model.ProxyModelHandler)pmHandlers[1];
    }

    public void handlerPMMessage(NetMessageO msg)
    {
        for (int i = 0; i < pmHandlers.Count; ++i)
        {
            pmHandlers[i].handlerUpdateMessage(msg);
        }
    }

    void Start ()
    {
        triggers.Add(new PingPongTimeTrigger());
    }

	void Update ()
    {
        for (int i = 0; i < triggers.Count; ++i)
        {
            triggers[i].tryTrigger(Time.deltaTime);
        }
    }
}


class PingPongTimeTrigger : TimeTrigger
{
    public PingPongTimeTrigger()
    {
        stepTime = 5.0f;
    }
    
    public override void trigger()
    {
        Debugger.Log("尝试心跳检测...");
        WebSocketConnect.instance.Pack((short)CommonChannel.EStartSyncTime);
    }
}



abstract class TimeTrigger
{

    float waitTime = 0.0f;
    protected float stepTime;

    public abstract void trigger();

    public void tryTrigger(float dt)
    {
        waitTime += dt;
        if (waitTime >= stepTime)
        {
            trigger();
            waitTime = 0.0f;
        }
    }
}
